<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 6.0.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.3/css/all.min.css" integrity="sha256-2H3fkXt6FEmrReK448mDVGKb3WW2ZZw35gI7vqHOE4Y=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"example.com","root":"/","images":"/images","scheme":"Gemini","version":"8.7.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>
<meta name="description" content="创建 Class 组件 ES6 方式 1234567891011import React from &amp;#x27;react&amp;#x27;class B extends React.Component&amp;#123;    constructor(props)&amp;#123;        super(props)    &amp;#125;    render()&amp;#123;        return (&lt;">
<meta property="og:type" content="article">
<meta property="og:title" content="react类组件">
<meta property="og:url" content="http://example.com/2021/11/24/39/index.html">
<meta property="og:site_name" content="Xiaolong&#39;s Blog">
<meta property="og:description" content="创建 Class 组件 ES6 方式 1234567891011import React from &amp;#x27;react&amp;#x27;class B extends React.Component&amp;#123;    constructor(props)&amp;#123;        super(props)    &amp;#125;    render()&amp;#123;        return (&lt;">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2021-11-24T12:27:39.000Z">
<meta property="article:modified_time" content="2022-02-22T13:15:29.346Z">
<meta property="article:author" content="Xiaolong">
<meta property="article:tag" content="react">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://example.com/2021/11/24/39/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"en","comments":true,"permalink":"http://example.com/2021/11/24/39/","path":"2021/11/24/39/","title":"react类组件"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>react类组件 | Xiaolong's Blog</title>
  




  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">Xiaolong's Blog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>Search
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="Searching..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA-Class-%E7%BB%84%E4%BB%B6"><span class="nav-number">1.</span> <span class="nav-text">创建 Class 组件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#props"><span class="nav-number">2.</span> <span class="nav-text">props</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BC%A0%E5%85%A5-props-%E7%BB%99-B-%E7%BB%84%E4%BB%B6"><span class="nav-number">2.1.</span> <span class="nav-text">传入 props 给 B 组件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%AF%BB%E5%8F%96"><span class="nav-number">2.2.</span> <span class="nav-text">读取</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#props-%E7%9A%84%E4%BD%9C%E7%94%A8"><span class="nav-number">2.3.</span> <span class="nav-text">props 的作用</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#state-amp-setState"><span class="nav-number">3.</span> <span class="nav-text">state &amp; setState</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="nav-number">3.1.</span> <span class="nav-text">初始化</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%AF%BB%E5%86%99-State"><span class="nav-number">3.2.</span> <span class="nav-text">读写 State</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%AF%BB-this-state"><span class="nav-number">3.2.1.</span> <span class="nav-text">读 this.state</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%86%99-this-setState-fn"><span class="nav-number">3.2.2.</span> <span class="nav-text">写 this.setState(???,fn)</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F"><span class="nav-number">4.</span> <span class="nav-text">生命周期</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%B1%BB%E6%AF%94%E5%A6%82%E4%B8%8B%E4%BB%A3%E7%A0%81"><span class="nav-number">4.1.</span> <span class="nav-text">类比如下代码</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%87%BD%E6%95%B0%E5%88%97%E8%A1%A8"><span class="nav-number">4.2.</span> <span class="nav-text">函数列表</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%87%BD%E6%95%B0%E5%88%97%E8%A1%A8-%E5%BF%85%E4%BC%9A"><span class="nav-number">4.3.</span> <span class="nav-text">函数列表-必会</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#constructor-%E5%9C%A8%E8%BF%99%E9%87%8C%E5%88%9D%E5%A7%8B%E5%8C%96-state"><span class="nav-number">4.3.1.</span> <span class="nav-text">constructor() - 在这里初始化 state</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#shouldComponentUpdate-return-false-%E9%98%BB%E6%AD%A2%E6%9B%B4%E6%96%B0"><span class="nav-number">4.3.2.</span> <span class="nav-text">shouldComponentUpdate() - return false 阻止更新</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#render-%E5%88%9B%E5%BB%BA%E8%99%9A%E6%8B%9F-DOM"><span class="nav-number">4.3.3.</span> <span class="nav-text">render() - 创建虚拟 DOM</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#componentDidMount-%E7%BB%84%E4%BB%B6%E5%B7%B2%E5%87%BA%E7%8E%B0%E5%9C%A8%E9%A1%B5%E9%9D%A2"><span class="nav-number">4.3.4.</span> <span class="nav-text">componentDidMount() - 组件已出现在页面</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#componentDidUpdate-%E7%BB%84%E4%BB%B6%E5%B7%B2%E6%9B%B4%E6%96%B0"><span class="nav-number">4.3.5.</span> <span class="nav-text">componentDidUpdate() - 组件已更新</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#componentWillUnmount-%E7%BB%84%E4%BB%B6%E5%B0%86%E6%AD%BB"><span class="nav-number">4.3.6.</span> <span class="nav-text">componentWillUnmount() - 组件将死</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#constructor-NaN"><span class="nav-number">5.</span> <span class="nav-text">constructor</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#shouldComponentUpdate"><span class="nav-number">6.</span> <span class="nav-text">shouldComponentUpdate</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#render"><span class="nav-number">7.</span> <span class="nav-text">render</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#componentDidMount"><span class="nav-number">8.</span> <span class="nav-text">componentDidMount()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#componentDidUpdate"><span class="nav-number">9.</span> <span class="nav-text">componentDidUpdate()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#componentWillUnmount"><span class="nav-number">10.</span> <span class="nav-text">componentWillUnmount()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E5%9B%9E%E9%A1%BE"><span class="nav-number">11.</span> <span class="nav-text">生命周期回顾</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-overview">
            <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Xiaolong"
      src="/images/lion.jpg">
  <p class="site-author-name" itemprop="name">Xiaolong</p>
  <div class="site-description" itemprop="description">Never stop learning</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">45</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">17</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="https://github.com/drwna" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;drwna" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>



          </div>
        </div>
      </div>
        <div class="back-to-top animated" role="button" aria-label="Back to top">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/Drwna" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="en">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/11/24/39/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/lion.jpg">
      <meta itemprop="name" content="Xiaolong">
      <meta itemprop="description" content="Never stop learning">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Xiaolong's Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          react类组件
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2021-11-24 20:27:39" itemprop="dateCreated datePublished" datetime="2021-11-24T20:27:39+08:00">2021-11-24</time>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="创建-Class-组件"><a href="#创建-Class-组件" class="headerlink" title="创建 Class 组件"></a>创建 Class 组件</h2><ol>
<li><p>ES6 方式</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="title class_">React</span> <span class="keyword">from</span> <span class="string">&#x27;react&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">B</span> <span class="keyword">extends</span> <span class="title class_ inherited__">React.Component</span>&#123;</span><br><span class="line">    <span class="title function_">constructor</span>(<span class="params">props</span>)&#123;</span><br><span class="line">        <span class="variable language_">super</span>(props)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">render</span>(<span class="params"></span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> (<span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span>hi<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> B</span><br></pre></td></tr></table></figure>

<span id="more"></span></li>
</ol>
<ol start="2">
<li><p>ES5 方式（过时）</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="title class_">React</span> <span class="keyword">from</span> <span class="string">&#x27;react&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> A = <span class="title class_">React</span>.<span class="title function_">createClass</span>(&#123;</span><br><span class="line">    <span class="title function_">render</span>(<span class="params"></span>)&#123;</span><br><span class="line">        <span class="keyword">return</span>(<span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span>hi<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> A</span><br><span class="line"><span class="comment">// 由于 ES5 不支持 class，才会有这种方法</span></span><br></pre></td></tr></table></figure></li>
</ol>
<h2 id="props"><a href="#props" class="headerlink" title="props"></a>props</h2><h3 id="传入-props-给-B-组件"><a href="#传入-props-给-B-组件" class="headerlink" title="传入 props 给 B 组件"></a>传入 props 给 B 组件</h3><figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Parent</span> <span class="keyword">extends</span> <span class="title class_ inherited__">React.Component</span> &#123;</span><br><span class="line">    <span class="title function_">constructor</span>(<span class="params">props</span>)&#123;</span><br><span class="line">        <span class="variable language_">super</span>(props)</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">state</span> = &#123;<span class="attr">name</span>: <span class="string">&#x27;frank&#x27;</span>&#125;</span><br><span class="line">    &#125;</span><br><span class="line">    onClick = <span class="function">() =&gt;</span> &#123;&#125;</span><br><span class="line">    <span class="title function_">render</span>(<span class="params"></span>)&#123;</span><br><span class="line">        <span class="keyword">return</span>(</span><br><span class="line">        <span class="language-xml"><span class="tag">&lt;<span class="name">B</span> <span class="attr">name</span>=<span class="string">&#123;this.state.n&#125;</span> <span class="attr">onClick</span>=<span class="string">&#123;this.onClick&#125;</span>&gt;</span>hi<span class="tag">&lt;/<span class="name">B</span>&gt;</span></span></span><br><span class="line">        )</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 外部数据被封装为一个对象</span></span><br><span class="line"><span class="comment">// &#123;name: &#x27;frank&#x27;, onClick:...,children: &#x27;hi&#x27;&#125;</span></span><br></pre></td></tr></table></figure>

<br />

<p>###初始化</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">B</span> <span class="keyword">extends</span> <span class="title class_ inherited__">React.Component</span>&#123;</span><br><span class="line">    <span class="title function_">constructor</span>(<span class="params">props</span>)&#123;</span><br><span class="line">        <span class="variable language_">super</span>(props)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">render</span>(<span class="params"></span>)&#123;...&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// this.props 就是外部数据 对象的地址 了</span></span><br></pre></td></tr></table></figure>

<br />

<h3 id="读取"><a href="#读取" class="headerlink" title="读取"></a>读取</h3><figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">B</span> <span class="keyword">extends</span> <span class="title class_ inherited__">React.Component</span>&#123;</span><br><span class="line">    <span class="title function_">constructor</span>(<span class="params">props</span>)&#123;</span><br><span class="line">        <span class="variable language_">super</span>(props)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">render</span>(<span class="params"></span>)&#123;</span><br><span class="line">        <span class="keyword">return</span>(</span><br><span class="line">            <span class="language-xml"><span class="tag">&lt;<span class="name">div</span> <span class="attr">onClick</span>=<span class="string">&#123;this.props.onClick&#125;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">            &#123;this.props.name&#125;</span></span><br><span class="line"><span class="language-xml">                <span class="tag">&lt;<span class="name">div</span>&gt;</span>&#123;this.props.chrldren&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">            <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">        )</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 通过 this.props.xxx 读取</span></span><br></pre></td></tr></table></figure>



<h3 id="props-的作用"><a href="#props-的作用" class="headerlink" title="props 的作用"></a>props 的作用</h3><p>接受外部数据</p>
<ul>
<li>只能读不能写</li>
<li>外部数据由父组件传递</li>
</ul>
<p>接受外部函数</p>
<ul>
<li>在恰当的时机，调用该函数</li>
<li>该函数一般是父组件的函数</li>
</ul>
<br />



<h2 id="state-amp-setState"><a href="#state-amp-setState" class="headerlink" title="state &amp; setState"></a>state &amp; setState</h2><h3 id="初始化"><a href="#初始化" class="headerlink" title="初始化"></a>初始化</h3><figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">B</span> <span class="keyword">extends</span> <span class="title class_ inherited__">React.Component</span> &#123;</span><br><span class="line">    <span class="title function_">constructor</span>(<span class="params">props</span>)&#123;</span><br><span class="line">        <span class="variable language_">super</span>(props)</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">state</span> = &#123;</span><br><span class="line">            <span class="attr">user</span>: &#123;</span><br><span class="line">                <span class="attr">name</span>: <span class="string">&#x27;frank&#x27;</span>,</span><br><span class="line">                <span class="attr">age</span>: <span class="number">18</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">render</span>(<span class="params"></span>)&#123;...&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br />

<h3 id="读写-State"><a href="#读写-State" class="headerlink" title="读写 State"></a>读写 State</h3><h4 id="读-this-state"><a href="#读-this-state" class="headerlink" title="读 this.state"></a>读 <code>this.state</code></h4><p><code>this.state.user.name</code></p>
<br />

<h4 id="写-this-setState-fn"><a href="#写-this-setState-fn" class="headerlink" title="写 this.setState(???,fn)"></a>写 <code>this.setState(???,fn)</code></h4><p><code>this.setState(newState, fn)</code></p>
<p>注意 setState 不会立刻改变 this.state，会在当前代码运行完后，再去更新 this.state，从而触发 UI 更新。（异步）</p>
<p><code>this.setState((state, props) =&gt; newState, fn)</code></p>
<p>这种方式的 state 更容易理解</p>
<p>fn 会在写入成功后执行。</p>
<p>shallow merge: setState 会自动将新的 state 与 旧的 state 进行一级合并。</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">onClick = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="variable language_">this</span>.<span class="title function_">setState</span>(&#123; <span class="attr">x</span>: <span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">x</span> + <span class="number">1</span> &#125;);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">onClick2 = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="variable language_">this</span>.<span class="title function_">setState</span>( <span class="function">(<span class="params">state</span>) =&gt;</span> (&#123; <span class="attr">x</span>: state.<span class="property">x</span> + <span class="number">2</span> &#125;) );</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">onClick = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="variable language_">this</span>.<span class="title function_">setState</span>(</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">x</span>: <span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">x</span> + <span class="number">1</span>,</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">// callback</span></span><br><span class="line">    <span class="function">() =&gt;</span> &#123;</span><br><span class="line">      <span class="variable language_">this</span>.<span class="title function_">setState</span>(&#123; <span class="attr">x</span>: <span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">x</span> + <span class="number">1</span> &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">  );</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>修改 this.state 的属性值，不推荐用！</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">x</span> += <span class="number">1</span></span><br><span class="line"><span class="variable language_">this</span>.<span class="title function_">setState</span>(<span class="variable language_">this</span>.<span class="property">state</span>)</span><br></pre></td></tr></table></figure>

<br />



<h2 id="生命周期"><a href="#生命周期" class="headerlink" title="生命周期"></a>生命周期</h2><p><strong><a target="_blank" rel="noopener" href="https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/">生命周期图谱</a></strong></p>
<br />

<h3 id="类比如下代码"><a href="#类比如下代码" class="headerlink" title="类比如下代码"></a>类比如下代码</h3><figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> div = <span class="variable language_">document</span>.<span class="title function_">createElement</span>(<span class="string">&#x27;div&#x27;</span>)</span><br><span class="line">这是 div 的 create / construct 过程</span><br><span class="line"></span><br><span class="line">div.<span class="property">textContent</span> = <span class="string">&#x27;hi&#x27;</span></span><br><span class="line">这是初始化 state</span><br><span class="line"></span><br><span class="line"><span class="variable language_">document</span>。body.<span class="title function_">appendChild</span>(div)</span><br><span class="line">这是 div 的 mount 过程</span><br><span class="line"></span><br><span class="line">div.<span class="property">textContent</span> = <span class="string">&#x27;hi2&#x27;</span></span><br><span class="line">这是 div 的 update 过程</span><br><span class="line"></span><br><span class="line">div.<span class="title function_">remove</span>()</span><br><span class="line">这是 div 的 unmount 过程</span><br></pre></td></tr></table></figure>

<br />

<h3 id="函数列表"><a href="#函数列表" class="headerlink" title="函数列表"></a>函数列表</h3><p><code>constructor()</code> </p>
<p><code>static getDerivedStateFromProps()</code></p>
<p><code>shouldComponentUpdate()</code></p>
<p><code>render()</code></p>
<p><code>getSnapshotBeforeUpdate()</code></p>
<p><code>componentDidMount()</code></p>
<p><code>componentDidUpdate()</code></p>
<p><code>componentWillUnmount()</code></p>
<p><code>static getDerivedStateFromError()</code></p>
<p><code>componentDidCatch()</code></p>
<br />



<h3 id="函数列表-必会"><a href="#函数列表-必会" class="headerlink" title="函数列表-必会"></a>函数列表-必会</h3><h4 id="constructor-在这里初始化-state"><a href="#constructor-在这里初始化-state" class="headerlink" title="constructor() - 在这里初始化 state"></a><code>constructor()</code> - 在这里初始化 state</h4><h4 id="shouldComponentUpdate-return-false-阻止更新"><a href="#shouldComponentUpdate-return-false-阻止更新" class="headerlink" title="shouldComponentUpdate() - return false 阻止更新"></a><code>shouldComponentUpdate()</code> - return false 阻止更新</h4><h4 id="render-创建虚拟-DOM"><a href="#render-创建虚拟-DOM" class="headerlink" title="render() - 创建虚拟 DOM"></a><code>render()</code> - 创建虚拟 DOM</h4><h4 id="componentDidMount-组件已出现在页面"><a href="#componentDidMount-组件已出现在页面" class="headerlink" title="componentDidMount() - 组件已出现在页面"></a><code>componentDidMount()</code> - 组件已出现在页面</h4><h4 id="componentDidUpdate-组件已更新"><a href="#componentDidUpdate-组件已更新" class="headerlink" title="componentDidUpdate() - 组件已更新"></a><code>componentDidUpdate()</code> - 组件已更新</h4><h4 id="componentWillUnmount-组件将死"><a href="#componentWillUnmount-组件将死" class="headerlink" title="componentWillUnmount() - 组件将死"></a><code>componentWillUnmount()</code> - 组件将死</h4><br />

<h2 id="constructor-NaN"><a href="#constructor-NaN" class="headerlink" title="constructor"></a>constructor</h2><p>用途：</p>
<p>初始化 props</p>
<p>初始化 state，但此时不能调用 setState</p>
<p>用来写 bind this</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">constructor</span>(<span class="params"></span>)&#123;</span><br><span class="line">    ...</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">onClick</span> = <span class="variable language_">this</span>.<span class="property">onClick</span>.<span class="title function_">bind</span>(<span class="variable language_">this</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以用新语法代替</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">constructor</span>(<span class="params"></span>)&#123;...&#125;</span><br><span class="line">onClick = <span class="function">() =&gt;</span> &#123;&#125;</span><br></pre></td></tr></table></figure>

<br />

<h2 id="shouldComponentUpdate"><a href="#shouldComponentUpdate" class="headerlink" title="shouldComponentUpdate"></a>shouldComponentUpdate</h2><p>用途：</p>
<p>返回 true 表示不阻止 UI 更新</p>
<p>返回 false 表示阻止 UI 更新</p>
<p>面试常问：shouldComponentUpdate 有什么用？</p>
<p>答：它允许我们手动判断是否要进行组件更新，我们可以根据应用场景灵活地设置返回值，以避免不必要地更新。</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="title class_">React</span> <span class="keyword">from</span> <span class="string">&quot;react&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">App</span> <span class="keyword">extends</span> <span class="title class_ inherited__">React.Component</span> &#123;</span><br><span class="line">  <span class="title function_">constructor</span>(<span class="params">props</span>) &#123;</span><br><span class="line">    <span class="variable language_">super</span>(props);</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">state</span> = &#123;</span><br><span class="line">      <span class="attr">n</span>: <span class="number">1</span>,</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;</span><br><span class="line">  onClick = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="title function_">setState</span>(<span class="function">(<span class="params">state</span>) =&gt;</span> (&#123; <span class="attr">n</span>: state.<span class="property">n</span> + <span class="number">1</span> &#125;));</span><br><span class="line">    <span class="variable language_">this</span>.<span class="title function_">setState</span>(<span class="function">(<span class="params">state</span>) =&gt;</span> (&#123; <span class="attr">n</span>: state.<span class="property">n</span> - <span class="number">1</span> &#125;));</span><br><span class="line">  &#125;;</span><br><span class="line">	<span class="comment">// &#123;n:1&#125; 和 &#123;n:1&#125;</span></span><br><span class="line">  <span class="title function_">shouldComponentUpdate</span>(<span class="params">nextProps, nextState</span>) &#123;</span><br><span class="line">      <span class="comment">// 阻止渲染</span></span><br><span class="line">    <span class="keyword">if</span> (nextState.<span class="property">n</span> === <span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">n</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="title function_">render</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;render了一次&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">      <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        App组件<span class="tag">&lt;<span class="name">br</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">        &#123;this.state.n&#125;</span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">button</span> <span class="attr">onClick</span>=<span class="string">&#123;this.onClick&#125;</span>&gt;</span>+1<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">    );</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="title class_">App</span>;</span><br></pre></td></tr></table></figure>



<p>可以使用 <code>React.PureComponent</code> 替代 <code>React.Component</code> 实现 shouldComponentUpdate()</p>
<p>PureComponent 会在 render 之前对比新 state 和旧 state 的每一个 key，以及新 props 和旧 props 的每一个 key。<br>如果所有 key 的值全都一样，就不会 render；如果有任何一个 key 的值不同，就会 render。</p>
<p><a target="_blank" rel="noopener" href="https://zh-hans.reactjs.org/docs/react-api.html#reactpurecomponent">官方文档</a></p>
<blockquote>
<p>注意</p>
<p><code>React.PureComponent</code> 中的 <code>shouldComponentUpdate()</code> 仅作对象的浅层比较。如果对象中包含复杂的数据结构，则有可能因为无法检查深层的差别，产生错误的比对结果。</p>
<p>仅在你的 props 和 state 较为简单时，才使用 <code>React.PureComponent</code>。</p>
</blockquote>
<br />



<h2 id="render"><a href="#render" class="headerlink" title="render"></a>render</h2><p>用途：</p>
<p>展示视图    <code>return (&lt;div&gt; ... &lt;/div&gt;)</code>，只能有一个根元素。</p>
<p>两个根元素，要用 <code>&lt;React.Fragment&gt;</code> 包起，可以缩写为 <code>&lt;&gt; &lt;/&gt;</code></p>
<p>技巧：</p>
<p>render 里面可以写 <code>if...else</code>、<code>?:</code>表达式</p>
<p>不能直接写 <code>for</code>循环，需要用数组</p>
<p>render 里面可以写 <code>aray.map</code>（循环）</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">App</span> <span class="keyword">extends</span> <span class="title class_ inherited__">React.PureComponent</span> &#123;</span><br><span class="line">  <span class="title function_">constructor</span>(<span class="params">props</span>) &#123;</span><br><span class="line">    <span class="variable language_">super</span>(props);</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">state</span> = &#123;</span><br><span class="line">      <span class="attr">n</span>: <span class="number">1</span>,</span><br><span class="line">      <span class="attr">array</span>: [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;</span><br><span class="line">  onClick = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="title function_">setState</span>(<span class="function">(<span class="params">state</span>) =&gt;</span> (&#123; <span class="attr">n</span>: state.<span class="property">n</span> + <span class="number">1</span> &#125;));</span><br><span class="line">  &#125;;</span><br><span class="line"><span class="comment">// if...else</span></span><br><span class="line">  <span class="title function_">render</span>(<span class="params"></span>) &#123;</span><br><span class="line">   <span class="keyword">let</span> message</span><br><span class="line">   <span class="keyword">if</span>(<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">n</span>%<span class="number">2</span> === <span class="number">0</span>)&#123;</span><br><span class="line">     message = <span class="language-xml"><span class="tag">&lt;<span class="name">span</span>&gt;</span>偶数<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span></span><br><span class="line">   &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">     message = <span class="language-xml"><span class="tag">&lt;<span class="name">span</span>&gt;</span>奇数<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span></span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">return</span>(</span><br><span class="line">     <span class="language-xml"><span class="tag">&lt;<span class="name">React.Fragment</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">     &#123;message&#125;</span></span><br><span class="line"><span class="language-xml">     <span class="tag">&lt;<span class="name">button</span> <span class="attr">onClick</span>=<span class="string">&#123;this.onClick&#125;</span>&gt;</span>+1<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">     <span class="tag">&lt;/<span class="name">React.Fragment</span>&gt;</span></span></span><br><span class="line">   )</span><br><span class="line">  &#125;</span><br><span class="line"><span class="comment">// ? :</span></span><br><span class="line">  <span class="title function_">render</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">      <span class="language-xml"><span class="tag">&lt;&gt;</span></span></span><br><span class="line"><span class="language-xml">        &#123;this.state.n % 2 === 0 ?</span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">span</span>&gt;</span>偶数<span class="tag">&lt;/<span class="name">span</span>&gt;</span> :</span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">span</span>&gt;</span>奇数<span class="tag">&lt;/<span class="name">span</span>&gt;</span>&#125;</span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">button</span> <span class="attr">onClick</span>=<span class="string">&#123;this.onClick&#125;</span>&gt;</span>+1<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/&gt;</span></span></span><br><span class="line">    );</span><br><span class="line">  &#125;</span><br><span class="line"><span class="comment">// for 循环</span></span><br><span class="line">  <span class="title function_">render</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> result = [];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">array</span>.<span class="property">length</span>; i++) &#123;</span><br><span class="line">      result.<span class="title function_">push</span>(<span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">array</span>[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">  &#125;</span><br><span class="line"><span class="comment">// for 循环 map()</span></span><br><span class="line"><span class="title function_">render</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="property">state</span>.<span class="property">array</span>.<span class="title function_">map</span>(<span class="function">(<span class="params">n</span>) =&gt;</span> <span class="language-xml"><span class="tag">&lt;<span class="name">span</span> <span class="attr">key</span>=<span class="string">&#123;n&#125;</span>&gt;</span>&#123;n&#125;<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br />

<h2 id="componentDidMount"><a href="#componentDidMount" class="headerlink" title="componentDidMount()"></a>componentDidMount()</h2><p>用途：</p>
<p>在元素插入页面后执行代码，这些代码依赖 DOM</p>
<p>比如，想获取 div 的高度，最好在这里写。</p>
<p>此处可以发起<strong>加载数据</strong>的 Ajax 请求（官方推荐）</p>
<p>首次渲染 会执行此钩子</p>
<p><a target="_blank" rel="noopener" href="https://zh-hans.reactjs.org/docs/react-component.html#componentdidmount">官方文档</a></p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 想获取 div 的高度</span></span><br><span class="line">...</span><br><span class="line"><span class="title function_">componentDidMount</span>(<span class="params"></span>)&#123;</span><br><span class="line">  <span class="keyword">const</span> div = <span class="variable language_">document</span>.<span class="title function_">querySelector</span>(<span class="string">&#x27;#xxx&#x27;</span>);</span><br><span class="line">  <span class="keyword">const</span> &#123;width&#125; = div.<span class="title function_">getBoundingClientRect</span>()</span><br><span class="line">  <span class="variable language_">this</span>.<span class="title function_">setState</span>(&#123;width&#125;)</span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">render</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="keyword">return</span>(</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&#x27;xxx&#x27;</span>&gt;</span>hello, width, &#123;this.state.width&#125;px<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">  )</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>改用 ref</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">App</span> <span class="keyword">extends</span> <span class="title class_ inherited__">React.PureComponent</span> &#123;</span><br><span class="line">  divRef = <span class="literal">undefined</span>;</span><br><span class="line">  <span class="title function_">constructor</span>(<span class="params">props</span>) &#123;</span><br><span class="line">    <span class="variable language_">super</span>(props);</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">state</span> = &#123;</span><br><span class="line">      <span class="attr">n</span>: <span class="number">1</span>,</span><br><span class="line">      <span class="attr">width</span>: <span class="literal">undefined</span>,</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">divRef</span> = <span class="title class_">React</span>.<span class="title function_">createRef</span>();</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  onClick = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="title function_">setState</span>(<span class="function">(<span class="params">state</span>) =&gt;</span> (&#123; <span class="attr">n</span>: state.<span class="property">n</span> + <span class="number">1</span> &#125;));</span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  <span class="title function_">componentDidMount</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">const</span> div = <span class="variable language_">this</span>.<span class="property">divRef</span>.<span class="property">current</span>;</span><br><span class="line">    <span class="keyword">const</span> &#123; width &#125; = div.<span class="title function_">getBoundingClientRect</span>();</span><br><span class="line">    <span class="variable language_">this</span>.<span class="title function_">setState</span>(&#123; width &#125;);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="title function_">render</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="language-xml"><span class="tag">&lt;<span class="name">div</span> <span class="attr">ref</span>=<span class="string">&#123;this.divRef&#125;</span>&gt;</span>hello, width: &#123;this.state.width&#125;px<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a target="_blank" rel="noopener" href="https://zh-hans.reactjs.org/docs/refs-and-the-dom.html">ref 官方文档</a></p>
<br />



<h2 id="componentDidUpdate"><a href="#componentDidUpdate" class="headerlink" title="componentDidUpdate()"></a>componentDidUpdate()</h2><p>用途：</p>
<p>在视图更新后执行。第一次渲染不执行。</p>
<p>此处也可以发起 Ajax 请求，用于<strong>更新数据</strong> （<a target="_blank" rel="noopener" href="https://zh-hans.reactjs.org/docs/react-component.html#componentdidupdate">文档</a>）。</p>
<p>首次渲染<strong>不会</strong> 执行此钩子。</p>
<p>在此处 setState 可能会引起无限循环，除非放在 if 里。</p>
<p>若 shouldComponentUpdate 返回 false，则不会触发此钩子。</p>
<br />



<h2 id="componentWillUnmount"><a href="#componentWillUnmount" class="headerlink" title="componentWillUnmount()"></a>componentWillUnmount()</h2><p>用途：</p>
<p>组件将要 <strong>被移出页面 然后被销毁</strong> 时执行代码</p>
<p>unmount 过的组件不会再次 mount</p>
<p>举例：</p>
<ul>
<li><p>如果你在 c…DidMount 里面监听了 window scroll</p>
<p>那么你就要在 c…WillUnmount 里面取消监听</p>
</li>
<li><p>如果你在 c…DidMount 里面创建了 Timer</p>
<p>那么你就要在 c…WillUnmout 里面取消 Timer</p>
</li>
<li><p>如果你在 c…DidMount 里面创建了 Ajax 请求</p>
<p>那么你就要在 c…WillUnmount 里面取消请求</p>
</li>
<li><p>否则你就是菜逼。</p>
</li>
</ul>
<p><a target="_blank" rel="noopener" href="https://zh-hans.reactjs.org/docs/react-component.html#componentwillunmount">官方文档</a></p>
<br />



<h2 id="生命周期回顾"><a href="#生命周期回顾" class="headerlink" title="生命周期回顾"></a>生命周期回顾</h2><ul>
<li><p><code>constructor()</code> - 在这里初始化 state</p>
</li>
<li><p><code>shouldComponentUpdate()</code> - return false 阻止更新</p>
</li>
<li><p><code>render()</code> - 创建虚拟 DOM</p>
</li>
<li><p><code>componentDidMount()</code> - 组件已出现在页面</p>
</li>
<li><p><code>componentDidUpdate()</code> - 组件已更新</p>
</li>
<li><p><code>componentWillUnmount()</code> - 组件将死</p>
</li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/react/" rel="tag"><i class="fa fa-tag"></i> react</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/11/24/51/" rel="prev" title="react函数组件">
                  <i class="fa fa-chevron-left"></i> react函数组件
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/12/11/14/" rel="next" title="react hooks 详解">
                  react hooks 详解 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2021 – 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Xiaolong</span>
</div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/third-party/search/local-search.js"></script>




  





</body>
</html>
